// import * as WebSocket from 'ws';
import * as jspb from 'google-protobuf';


// 假设您的proto文件已经被编译为UserProto.js，并且可以从当前模块访问到
import proto from '../../Proto.js/proto.js' // 替换为您实际生成的protobuf js模块路径
import { Label, log } from 'cc';
import protobuf from 'protobufjs';

export class ProtobufWebSocketClient {
  public socket: WebSocket;
  private chatFrame: Label; 

  constructor(url: string, chatFrame: Label) {
    this.chatFrame = chatFrame;
    this.socket = new WebSocket(url);
    this.socket.binaryType = "arraybuffer"; // 设置接收二进制数据为ArrayBuffer类型

    
    this.socket.onopen = () => {
        console.log('WebSocket connection opened');

        // 创建一个User对象实例
        const chatMessage = new proto.ChatMessage();
        chatMessage.sender = '私聊';
        chatMessage.messageText = 'hello';
        chatMessage.timestamp = Date.now(); // 使用当前时间戳

        // 创建一个writer来写入二进制数据
        const writer = new protobuf.Writer()

        // 调用ChatMessage静态方法encode进行编码
        proto.ChatMessage.encode(chatMessage, writer);

        // 获取编码后的二进制数据
        const encodedData = writer.finish();

        const originalData = {
          sender: chatMessage.sender,
          messageText: chatMessage.messageText,
          timestamp: chatMessage.timestamp
        };
        const originalJsonSize = JSON.stringify(originalData).length;
        const protobufSerializedSize = encodedData.byteLength;

        console.log(`Original JSON size: ${originalJsonSize} bytes`);
        console.log(`Protobuf serialized size: ${protobufSerializedSize} bytes`);
        const compressionRate = (1 - (protobufSerializedSize / originalJsonSize)) * 100;
        console.log(`压缩率: ${compressionRate.toFixed(2)}%`);

        // 发送编码后的数据
        // 立即发送此消息
        // this.sendMessage(chatMessage);
        this.socket.send(encodedData);
    };

    this.socket.onmessage = (event) => {

      if (event.data instanceof ArrayBuffer) {
        // 在这里处理接收到的protobuf二进制数据，例如：
        const bytes = new Uint8Array(event.data);

      // 解析protobuf二进制数据为ChatMessage对象
        const chatMessage = proto.ChatMessage.decode(bytes);

        var dateObject = new Date(chatMessage.timestamp);
        var dateString = dateObject.getFullYear() + '-' 
               + (dateObject.getMonth() + 1) + '-' 
               + dateObject.getDate() + ' '
               + ('0' + dateObject.getHours()).slice(-2) + ':'
               + ('0' + dateObject.getMinutes()).slice(-2) + ':'
               + ('0' + dateObject.getSeconds()).slice(-2);

        this.chatFrame.getComponent(Label).string += '\n' + '[' + dateString + '] ' +chatMessage.messageText;
        log('返回的数据', chatMessage)
      }
    };

    this.socket.onclose = () => {
      console.log('WebSocket connection closed');
    };
  }

  /**
   * 发送protobuf消息到WebSocket服务器。
   * @param user 用户信息的protobuf消息实例
   */
  sendMessage(data: string) {
    // 将User对象序列化为二进制数据
    // const binaryData = user.serializeBinary();

    // 检查WebSocket连接是否已建立
    if (this.socket.readyState === WebSocket.OPEN) {
      // 发送protobuf编码后的二进制数据

      // 创建一个User对象实例
      const chatMessage = new proto.ChatMessage();
      chatMessage.sender = '私聊';
      chatMessage.messageText = data;
      chatMessage.timestamp = Date.now(); // 使用当前时间戳

      // 创建一个writer来写入二进制数据
      const writer = new protobuf.Writer()

      // 调用ChatMessage静态方法encode进行编码
      proto.ChatMessage.encode(chatMessage, writer);

      // 获取编码后的二进制数据
      const encodedData = writer.finish();

      this.socket.send(encodedData);
    } else {
      console.error('WebSocket connection is not open. Cannot send message.');
    }
  }

}

// 使用客户端
// const client = new ProtobufWebSocketClient('ws://127.0.0.1:6666/websocket');